package com.suxin.thread.schedulev2;

import com.suxin.thread.schedule.task.Task;
import com.suxin.thread.schedule.task.TaskService;
import com.suxin.thread.schedulev2.error.ExecutorErrorHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Tang
 * @classname TaskExecutorThread
 * @description [  ]
 * @date 2021/6/10 15:25
 */
@Service
@Slf4j
public class TaskExecutorThread implements Runnable {

    private Task task;

    private int jobLogId;

    private int taskLogId;

    private CountDownLatch countDownLatch;

    private ExecutorErrorHandler executorErrorHandler;

    private ThreadPoolExecutor currentTaskExecutorThreadPool;

    @Resource
    TaskService taskService;

    public TaskExecutorThread(int logId, Task task,
                              ExecutorErrorHandler executorErrorHandler, CountDownLatch countDownLatch) {
        this.task = task;
        this.jobLogId = logId;
        this.countDownLatch = countDownLatch;
        this.executorErrorHandler = executorErrorHandler;
        currentTaskExecutorThreadPool = JobExecutorContext.getCurrentTaskExecutorThreadPool(jobLogId);
    }

    @Override
    public void run() {
        TaskResult taskResult = null;
        // 当前任务是否被中断
        boolean isInterrupted = false;
        // 当前任务是否已执行
        boolean realStarted = false;
        String preTaskIds = task.getPreTaskIds();
        try {
            // 没有前置任务
            if (StringUtils.isEmpty(preTaskIds) || isAllPreHasFish(preTaskIds)) {
                log.info("子任务开始执行,jobId:{},taskId:{}", task.getJobId(), task.getId());
                realStarted = true;
                // 执行开始，记录状态及日志
                refreshAndLogStart();
                // 执行具体逻辑，等待结果执行完成
                taskResult = taskService.executeTask(task.getId());
                log.info("子任务执行结束,jobId:{},taskId:{}", task.getJobId(), task.getId());
            } else {
                log.info("前置子任务尚未完成，等待后续执行，jobId:{},taskId:{}", task.getJobId(), task.getId());
                JobExecutorContext.sleepIfIdle(currentTaskExecutorThreadPool);
                // 重新进入队列等待执行，
                currentTaskExecutorThreadPool.execute(this);
            }
        } catch (Exception e) {
            if (e instanceof InterruptedException || Thread.currentThread().isInterrupted()) {
                isInterrupted = true;
                log.warn("其他子任务执行失败导致终止执行，当前子任务已执行,jobId:{}",task.getJobId());
                taskResult = null;
            }else {
                // 任务没有执行
                if (!realStarted) {
                    log.warn("其他子任务执行失败导致终止执行,当前子任务未执行,jobId:{}",task.getJobId());
                }else {
                    log.error("子任务执行失败,jobId:{}, taskId:{}", task.getJobId(), task.getId(), e);
                    taskResult = null;
                }
            }
        }finally {

            if (taskResult != null && realStarted) {
                refreshAndLogFinish(taskResult);
            }

            if (!isInterrupted) {
                this.countDownLatch.countDown();
                // 失败策略处理
                if (!taskResult.isSuccess()) {
                    executorErrorHandler.handlerTaskError(this,taskResult);
                }
            }

        }

    }

    private void refreshAndLogFinish(TaskResult taskResult) {

    }

    private void refreshAndLogStart() {

    }

    private boolean isAllPreHasFish(String preTaskIds) {
        return false;
    }

}